﻿@using System.Reflection
@using AntDesign.Docs.Localization
@using System.Globalization

<ConfigProvider>
    <Router AppAssembly="typeof(App).Assembly" OnNavigateAsync="OnNavigateAsync">
        <Found Context="routeData">
            <RouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)" />
            <FocusOnNavigate RouteData="routeData" Selector="h1" />
        </Found>
        <NotFound>
            <Result Status="404" />
        </NotFound>
    </Router>
    <AntContainer />
</ConfigProvider>

@inject ILanguageService LanguageService;
@inject NavigationManager NavigationManager;
@code{
    async Task OnNavigateAsync(NavigationContext navigationContext)
    {
        var relativeUri = navigationContext.Path;
        var currentCulture = LanguageService.CurrentCulture;

        var segment = relativeUri.IndexOf('/') > 0 ? relativeUri.Substring(0, relativeUri.IndexOf('/')) : relativeUri;

        try
        {
            if (string.IsNullOrWhiteSpace(segment))
            {
                NavigationManager.NavigateTo($"{currentCulture.Name}/{relativeUri}");
                return;
            }
            else
            {
                if (segment.IsIn("zh-CN", "en-US"))
                {
                    LanguageService.SetLanguage(CultureInfo.GetCultureInfo(segment));
                }
                else if (currentCulture.Name.IsIn("zh-CN", "en-US"))
                {
                    NavigationManager.NavigateTo($"{currentCulture.Name}/{relativeUri}");
                }
                else
                {
                    NavigationManager.NavigateTo($"en-US/{relativeUri}");
                    return;
                }
            }
        }
        catch
        {
            
        }
    }
}